Pointer in C

A Pointer variable is used to store the address of an other variable instead of store the value in its address.

Pointers are used to access memory and manipulate the address.

Whenever we define a variable in C, a memory location is assigned to it, to which the value assigned to the variable will be stored.

The address is denoted by the symbol &.So if we declare a variable named x the to denote the address of the variable x we specify &x.

Example

 #include<stdio.h>
 
 void main()
 {
     int a = 10;
     printf("Value of a is: %d\n", a);
     printf("Memory address of a is: %u\n", &a);
 }

Output

 Value of a is: 10
 Memory address of a is: bcc7a01

We might have noticed that when getting input from the user we use the scanf() function. There we will mention & to denote the address of the variable.

Example

scanf("%d",&a);

Declaring a pointer variable

In order to define a pointer variable we use the below syntax.

 datatype *pointer_name;

Example

 int *ptr;

Initializing a pointer variable

In order to initialize the pointer variable we usually assign the address of a variable to the pointer variable. It will hold the address of a variable of same type.

Example

 int x = 10;
 int *ptr;       //pointer declaration
 ptr = &x;       //pointer initialization

pointers in c

If we try to assign the address of different type to the pointer variable, then it will throw an error.

If we declare a pointer variable and does not assign any address to it, then it will contain garbage value. So it is recommended to assign NULL value to the variable.

Example

int *ptr = NULL;

Once a pointer has been assigned the address of a variable, to access the value of the variable, the pointer is dereferenced, using the indirection operator or dereferencing operator *. Consider the following example for better understanding.

Example program

 #include <stdio.h>
 
 int main()
 {
     int a;  
     a = 20;
     int *p = &a;     // declaring and initializing the pointer
 
     //prints the value of "a"
     printf("%d\n", *p);  
     printf("%d\n", *&a);  
     //prints the address of "a"
     printf("%u\n", &a);    
     printf("%u\n", p);     
     
     printf("%u\n", &p);    //prints address of p
     
     return 0;
 }

Output

 20
 20
 4395480300
 4395480300
 4395480304

Note

  • Declaring a pointer variable should contain * before the variable.
  • Pointer variable stores the address of a variable.
  • To get the value stored in the address that is stored in the pointer variable, we use *variable_name.

Most Read